package cn.itcast.javaee.springmvc.app10;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractCommandController;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 作者：13687
 * 日期：2017/3/26
 * 项目：SpringMVC64
 * 描述：单例；
 * 1. 封装请求参数
 * 2. 类型转换
 * AbstractCommandController 提供验证表单的功能
 */

public class UserAction extends AbstractCommandController {

	public UserAction() {
		// 设置封装类
		setCommandClass(User.class);
	}

	/**
	 * @param request
	 * @param binder 注册转换器
	 * @throws Exception
	 */
	@Override
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
//		super.initBinder(request, binder);
//		将指定格式的日期 Date
		binder.registerCustomEditor(Date.class,
				new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),false));
	}

	@Override
	protected ModelAndView handle(HttpServletRequest httpServletRequest,
	                              HttpServletResponse httpServletResponse,
	                              Object o,
	                              BindException e) throws Exception {
		e.printStackTrace();

		ModelAndView modelAndView = new ModelAndView();
		// 接收参数
		User user = (User) o;

		System.out.println(this.getClass().getSimpleName() + ":handle === "+user.toString());

		modelAndView.addObject("user",user);
		modelAndView.setViewName("/jsp/success.jsp");
		return modelAndView;
	}
}
